<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="spu名称"
        ><span>{{ data.spuName }}</span></el-form-item
      >
      <el-form-item label="sku名称"
        ><el-input placeholder="sku名称" v-model="formData.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格"
        ><el-input-number
          placeholder="价格"
          v-model="formData.price"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="重量"
        ><el-input-number
          placeholder="重量"
          v-model="formData.weight"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="描述"
        ><el-input
          type="textarea"
          placeholder="描述"
          v-model="formData.skuDesc"
          rows="5"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form inline>
          <el-form-item
            v-for="(item, index) in skuAttrValueList"
            :key="item.categoryId"
            :label="item.attrName"
            :label-width="100"
            style="margin-bottom: 20px"
          >
            <el-select v-model="selectAttrList[index]">
              <el-option
                :label="item2.valueName"
                :value="`${item.id}|${item2.id}`"
                v-for="item2 in item.attrValueList"
                :key="item2.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form inline>
          <el-form-item
            v-for="(item, index) in saleAttrSelect"
            :key="item.baseSaleAttrId"
            :label="item.saleAttrName"
            :label-width="100"
            style="margin-bottom: 20px"
          >
            <el-select v-model="selectSaleList[index]">
              <el-option
                :label="item2.saleAttrValueName"
                :value="`${item.id}|${item2.id}`"
                v-for="item2 in item.spuSaleAttrValueList"
                :key="item2.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table
          :data="spuImgList"
          @selection-change="selectChange"
          ref="imgListRef"
          v-loading="loading"
        >
          <el-table-column type="selection"> </el-table-column>
          <el-table-column label="图片">
            <template #="{ row }">
              <img :src="row.imgUrl" alt="" style="width: 100px" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #="{ row }">
              <el-button
                type="primary"
                v-if="row.id == isDefault"
                @click="myDefault(row)"
                color="green"
                >取消默认</el-button
              >
              <el-button type="primary" v-else @click="myDefault(row)"
                >设为默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="comfirmAttrList">保存</el-button>
        <el-button type="primary" @click="comeBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "SkuForm",
});
</script>
<script setup lang="ts">
import { ref } from "vue";

import type { recordsType, spuSaleAttrListType, spuImageList } from "@/api/spu";
import { reqSpuSaleAttrList, reqSpuImgList } from "@/api/spu";
import type { saveSkuInfoType, skuImageListType } from "@/api/sku";
import { reqSaveSkuInfo } from "@/api/sku";
import { reqAttrInfoList } from "@/api/attr";
import type { attrInfoType } from "@/api/category";
import VIEW_TYPE from "../../viewType";
//pinia
import getCategoryStore from "@/stores/category";
import { storeToRefs } from "pinia";
const loading = ref(false);
const categoryStore = getCategoryStore();
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);
//1、获取基本props参数
const props = defineProps<{ data: recordsType }>();
// console.log("props", props.data);
// 2、数据初始化
const formData = ref<saveSkuInfoType>({
  spuId: props.data.id,
  // 所属品牌ID
  tmId: props.data.tmId,
  // 所属分类ID
  category3Id: props.data.category3Id,

  // SKU名称
  skuName: "",
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // sku规格描述
  skuDesc: "",
  // sku默认图片
  skuDefaultImg: "",
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});
//attrList列表ref
const skuAttrValueList = ref<attrInfoType[]>();
//获取列表数据

const getSelectAttr = async () => {
  try {
    loading.value = true;
    skuAttrValueList.value = await reqAttrInfoList(
      category1Id.value as number,
      category2Id.value as number,
      category3Id.value as number
    );
    loading.value = false;
  } catch (e) {
    ElMessage.error("获取失败");
  }
};
getSelectAttr();
//获取销售属性
const saleAttrSelect = ref<spuSaleAttrListType[]>([]);
const getSaleAttrListType = async () => {
  try {
    saleAttrSelect.value = await reqSpuSaleAttrList(props.data.id);
  } catch (e) {
    ElMessage.error("获取销售属性失败");
  }
};
getSaleAttrListType();
//v-model用数组形式绑定select
const selectAttrList = ref<string[]>([]);
const selectSaleList = ref<string[]>([]);

//获取初始化imgList列表
const spuImgList = ref<spuImageList[]>([]);
const getSpuImgLIst = async () => {
  try {
    spuImgList.value = await reqSpuImgList(props.data.id);
  } catch (e) {
    ElMessage.error("获取图片错误");
  }
};
getSpuImgLIst();
// 获取select事件 暂时没用
// const selectImgItem = (a: any) => {
//   console.log("a", a);
// };
// const selectImgAll = (b: any) => {
//   console.log("b", b);
// };
const selectChange = (select: spuImageList[]) => {
  console.log("c", select);
  formData.value.skuImageList = select.map((item) => {
    return {
      ...item,
      isDefault: false,
    } as skuImageListType;
  });
};
//将获取的imgList 填入formData
//表格ref
const imgListRef = ref();
//设置保存变量
let isDefault = ref<number>(0);
const myDefault = (row: spuImageList) => {
  //寻找是否已有默认
  const isDefaultExist = formData.value.skuImageList.find((item) => {
    return item.id == isDefault.value;
  });
  if (isDefaultExist) {
    isDefaultExist.isDefault = false;
  }
  if (row.id === isDefault.value) {
    isDefault.value = 0;
  } else {
    //已选择数据中是否存在
    const formDataExsit = formData.value.skuImageList.find(
      (item: any) => item.id == row.id
    );
    if (formDataExsit) {
      formDataExsit.isDefault = true;
      isDefault.value = formDataExsit.id;
    } else {
      isDefault.value = row.id as number;
      imgListRef.value.toggleRowSelection(row, true);
    }
  }
};
//保存已选中
const emit = defineEmits(["change-view"]);
const comfirmAttrList = async () => {
  //分割attr
  // const [attrId,valueId]=selectAttrList.value
  selectAttrList.value.forEach((item) => {
    const [attrId, valueId] = item.split("|");

    formData.value.skuAttrValueList.push({
      attrId: Number(attrId),
      valueId: Number(valueId),
    });
  });
  //分割sale
  selectSaleList.value.forEach((item) => {
    // console.log("1");

    const [saleAttrId, saleAttrValueId] = item.split("|");

    formData.value.skuSaleAttrValueList.push({
      saleAttrId: Number(saleAttrId),
      saleAttrValueId: Number(saleAttrValueId),
    });
  });
  //将已选中的imgDefaultImg
  const skuDefaultImgExist = formData.value.skuImageList.find(
    (item) => item.isDefault
  );
  if (skuDefaultImgExist) {
    formData.value.skuDefaultImg = skuDefaultImgExist.imgUrl
      ? skuDefaultImgExist.imgUrl
      : "";
    console.log(
      "skuDefaultImgExist",
      skuDefaultImgExist,
      formData.value.skuDefaultImg
    );
  }
  //提交请求
  try {
    await reqSaveSkuInfo(formData.value);
    emit("change-view", VIEW_TYPE.LIST);
  } catch (e) {
    ElMessage.error("提交请求失败");
  }
};
const comeBack = () => {
  emit("change-view", VIEW_TYPE.LIST);
};
</script>
<style scoped></style>

